<?php

namespace app\common\business;


use app\common\lib\Str;
use app\common\lib\Time;
use think\Exception;

class User
{

    public $userObj = null;

    public function __construct()
    {
        $this->userObj = new \app\common\model\mysql\User();
    }

    public function login($date)
    {
        $redisCode = cache(config("redis.code_pre") . $date['phone_number']);
        if (empty($redisCode) || $redisCode != $date['code']) {
           //   throw  new Exception("不存在该验证码", -1009);
        }
        //判断 表是否有用户记录

        $user = $this->userObj->getUserByphoneNumber($date['phone_number']);


        //如果不存在用户 则生成新用户名
        if (!$user) {
            $username = '用户' . $date['phone_number'];
            $userDate = [
                'username' => $username,
                'phone_number' => $date['phone_number'],
                'type' => $date['type'],
                'status' => config('status.mysql.table_normal'),

            ];
            try {
                $this->userObj->save($userDate);
                $userId = $this->userObj->id;
            } catch (\Exception $e) {
                throw  new Exception('数据库内部异常');
            }

            //如果用户存在更新表
        } else {

            $userId = $user->id;
            $username = $user->username;

            $updateDate = [
                "last_login_time" => time(),
                "last_login_ip" => request()->ip(),
            ];
            try {
                $this->userObj->updateById($userId, $updateDate);
            } catch (\Exception $e) {
                throw  new Exception('数据库内部异常');
            }
        }

        //生成token
        $token = Str::getLoginToken($date['phone_number']);
        $redisDate = [
            "id" => $userId,
            "username" => $username,
        ];
        $res = cache(config("redis.token_pre") . $token, $redisDate, Time::userLoginExpiresTime($date['type']));

        //如果 值存在 就返回token
        return $res ? ["token" => $token, "username" => $username] : false;


    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserById($id)
    {
        //获取用户数据
        $user = $this->userObj->getUserById($id);
        if (!$user || $user->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $user->toArray();

    }

    /**
     * 返回正常用户数据
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalUserByUsername($username)
    {
        //获取用户数据
        $user = $this->userObj->getUserByUsername($username);
        if (!$user || $user->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $user->toArray();

    }


    public function update($id, $data)
    {
        $user = $this->getNormalUserById($id);
        if (!$user) {
            throw  new Exception("不存在该用户");
        }
        //检查用户是否存在
        $userResult = $this->getNormalUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id) {
            throw new Exception("该用户已经存在");
        }


        return $this->userObj->updateById($id, $data);
    }

}